import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import authApi from '../api/auth'

interface UserInfo {
  id?: number
  username: string
  nick_name?: string
  email?: string
  avatar?: string
  role?: string
  level?: number
  solved_problems?: number
  total_submissions?: number
  created_time?: string
  last_login?: string
  is_staff?: boolean
}

export const useUserStore = defineStore('user', () => {
  const userInfo = ref<UserInfo>({
    username: '',
    avatar: '',
    role: ''
  })
  const isLoggedIn = ref(false)

  async function fetchUserInfo() {
    try {
      const response = await authApi.getUserInfo()
      userInfo.value = response
      isLoggedIn.value = true
    } catch (error) {
      console.error('Failed to fetch user info:', error)
      isLoggedIn.value = false
      userInfo.value = { username: '', avatar: '', role: '' }
    }
  }

  function logout() {
    isLoggedIn.value = false
    userInfo.value = { username: '', avatar: '', role: '' }
  }

  return {
    userInfo,
    isLoggedIn,
    fetchUserInfo,
    logout
  }
})
